//
//  EDSVideoCropView.m
//  DrivieSchoolStudents
//
//  Created by TangBin on 2019/5/27.
//  Copyright © 2019 班文政. All rights reserved.
//

#import "EDSVideoCropView.h"
#import "EDSDragEditView.h"


#define EDGE_EXTENSION_FOR_THUMB 20

#define kPlayLineWidth (3.0) // 播放条的宽度

@interface EDSVideoCropView () <UIScrollViewDelegate>

@property (nonatomic, strong) UIScrollView *editScrollView;

@property (nonatomic, strong) UIView *topBorder;
@property (nonatomic, strong) UIView *bottomBorder;

@property (nonatomic, strong) EDSDragEditView *leftDragView; ///< 左边编辑框拖动条
@property (nonatomic, strong) EDSDragEditView *rightDragView; ///< 右边编辑框拖动条
@property (nonatomic, strong) UIView *playLine; ///< 播放滚动条


@property (nonatomic, assign) CGFloat   startTime;      ///< 编辑框内视频开始时间秒
@property (nonatomic, assign) CGFloat   endTime;        ///< 编辑框内视频结束时间秒
@property (nonatomic, assign) CGFloat   startPointX;    ///< 编辑框起始点
@property (nonatomic, assign) CGFloat   endPointX;      ///< 编辑框结束点
@property (nonatomic, assign) CGFloat   IMG_Width;      ///< 视频帧宽度
@property (nonatomic, assign) CGFloat   linePositionX;  ///< 播放条的位置
@property (nonatomic, assign) CGFloat   boderX;         ///< 编辑框边线X
@property (nonatomic, assign) CGFloat   boderWidth;     ///< 编辑框边线长度
@property (nonatomic, assign) CGFloat   touchPointX;    ///< 编辑视图区域外触点

@property (nonatomic, assign) BOOL      isDraggingRightOverlayView;
@property (nonatomic, assign) BOOL      isDraggingLeftOverlayView;
@property (nonatomic, assign) CGPoint   leftStartPoint;
@property (nonatomic, assign) CGPoint   rightStartPoint;

@property (nonatomic, strong) NSTimer           *lineMoveTimer; // 播放条移动计时器


- (void)initWithEditScrollView;

- (void)initWithTopBorder;
- (void)initWithBottomBorder;

- (void)initWithLeftDragView;
- (void)initWithRightDragView;

- (void)initWithPlayLine;

@end

@implementation EDSVideoCropView

- (instancetype)initWithFrame:(CGRect)frame seconds:(NSInteger)seconds
{
//    NSLog(@"tb---seconds=%d", seconds);
    if (seconds <= 60)
    {
        self.endTime = seconds;
    }
    else
    {
        self.endTime = kRECORD_VIDEO_TIME;
    }
    return [self initWithFrame:frame];
}

- (void)initWithVar
{
    [super initWithVar];
    
    self.boderX = 45.0f;
    self.boderWidth = kScreenWidth - self.boderX * 2;
    
    // 默认startTime 0秒；endTime 10秒
    self.startTime = 0;
//    self.endTime = kRECORD_VIDEO_TIME;
    self.startPointX = 50;
    self.endPointX = kScreenWidth  - 50;
    self.IMG_Width = (kScreenWidth - 50 *2) / 15;//self.endTime;
    
    
}

- (void)initWithSubView
{
    [super initWithSubView];
    self.backgroundColor = [UIColor colorWithHexString:@"#262625"];
    
    [self initWithEditScrollView];
    
    [self initWithTopBorder];
    [self initWithBottomBorder];
    
    [self initWithLeftDragView];
    [self initWithRightDragView];
    
    UIPanGestureRecognizer *panGestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(moveOverlayView:)];
    [self addGestureRecognizer:panGestureRecognizer];
    
    [self initWithPlayLine];
}

- (void)initWithEditScrollView
{
    if (!_editScrollView)
    {
        CGRect frame = self.bounds;
        _editScrollView = [[UIScrollView alloc] initWithFrame:frame];
        _editScrollView.showsHorizontalScrollIndicator = NO;
        _editScrollView.bounces = NO;
        _editScrollView.delegate = self;
        [self addSubview:_editScrollView];
    }
}

- (void)initWithTopBorder
{
    if (!_topBorder)
    {
        CGRect frame = CGRectMake(self.boderX, 0, self.boderWidth, 2);
        _topBorder = [[UIView alloc] initWithFrame:frame];
        _topBorder.backgroundColor = [UIColor whiteColor];
        [self addSubview:_topBorder];
    }
}
- (void)initWithBottomBorder
{
    if (!_bottomBorder)
    {
        CGRect frame = CGRectMake(self.boderX, self.height - 2, self.boderWidth, 2);
        _bottomBorder = [[UIView alloc] initWithFrame:frame];
        _bottomBorder.backgroundColor = [UIColor whiteColor];
        [self addSubview:_bottomBorder];
    }
}

- (void)initWithLeftDragView
{
    if (!_leftDragView)
    {
        // 表示这个视图，在屏幕上显示右边的50宽度
        CGRect frame = CGRectMake(-(kScreenWidth - kEDSVideoCropViewHeight), 0, kScreenWidth, kEDSVideoCropViewHeight);
        _leftDragView = [[EDSDragEditView alloc] initWithFrame:frame Left:YES];
        _leftDragView.hitTestEdgeInsets = UIEdgeInsetsMake(0, -(EDGE_EXTENSION_FOR_THUMB), 0, -(EDGE_EXTENSION_FOR_THUMB));
        [self addSubview:_leftDragView];
    }
}
- (void)initWithRightDragView
{
    if (!_rightDragView)
    {
        // 显示z50宽度，其它全部在屏幕之外
        CGRect frame = CGRectMake(kScreenWidth - 50, 0, kScreenWidth, 50);
        _rightDragView = [[EDSDragEditView alloc] initWithFrame:frame Left:NO];
        _rightDragView.hitTestEdgeInsets = UIEdgeInsetsMake(0, -(EDGE_EXTENSION_FOR_THUMB), 0, -(EDGE_EXTENSION_FOR_THUMB));
        [self addSubview:_rightDragView];
    }
}

- (void)initWithPlayLine
{
    if (!_playLine)
    {
        CGRect frame = CGRectMake(10, 0, kPlayLineWidth, 50);
        _playLine = [[UIView alloc] initWithFrame:frame];
        _playLine.backgroundColor = [UIColor colorWithRed:214/255.0 green:230/255.0 blue:247/255.0 alpha:1.0];
        [self addSubview:_playLine];
        _playLine.hidden = YES;
    }
}

- (void)addImageFrame:(long)count image:(UIImage *)image
{
    dispatch_async(dispatch_get_main_queue(), ^{
        UIImageView *thumImgView = [[UIImageView alloc] initWithFrame:CGRectMake(50+count*self.IMG_Width, 0, self.IMG_Width, 70)];
        thumImgView.image = image;
        [self.editScrollView addSubview:thumImgView];
        self.editScrollView.contentSize = CGSizeMake(100+count*self.IMG_Width, 0);
    });
}

- (void)startTimer
{
    self.playLine.hidden = NO;
    self.linePositionX = self.startPointX;
    self.lineMoveTimer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(lineMove) userInfo:nil repeats:YES];
}

- (void)stopTimer
{
    [self.lineMoveTimer invalidate];
    self.playLine.hidden = YES;
}

// 播放条移动
- (void)lineMove
{
    double durationTime = self.endTime - self.startTime;//(self.endPointX - self.startPointX - 20) / kScreenWidth * 10;
//    NSLog(@"dureee=%f", durationTime);
    self.linePositionX += 0.01 * (self.endPointX - self.startPointX - 20) / durationTime;
    if (self.linePositionX >= CGRectGetMinX(self.rightDragView.frame) - kPlayLineWidth)
    {
        self.linePositionX = CGRectGetMaxX(self.leftDragView.frame) + kPlayLineWidth;
    }
    self.playLine.frame = CGRectMake(self.linePositionX, 0, kPlayLineWidth, 50);
}

- (void)letScrollViewScrollAndResetPlayerStartTime
{
    CGFloat offsetX = self.editScrollView.contentOffset.x;
    CMTime startTime;
    if (offsetX >= 0)
    {
        startTime = CMTimeMakeWithSeconds((offsetX+self.startPointX)/self.IMG_Width, [self.delegate getCurrentTime]);
        CGFloat duration = self.endTime-self.startTime;
        self.startTime = (offsetX+self.startPointX)/self.IMG_Width;
        self.endTime = self.startTime + duration;
    }
    else
    {
        startTime = CMTimeMakeWithSeconds(self.startPointX, [self.delegate getCurrentTime]);
    }
    
    // 只有视频播放的时候才能够快进和快退1秒以内
    if (self.delegate && [self.delegate respondsToSelector:@selector(seekTotime:withBefore:withAfter:)])
    {
        [self.delegate seekTotime:startTime withBefore:kCMTimeZero withAfter:kCMTimeZero];
    }
}

#pragma mark - 编辑区域手势拖动
- (void)moveOverlayView:(UIPanGestureRecognizer *)gesture
{
    switch (gesture.state)
    {
        case UIGestureRecognizerStateBegan:
        {
            if (self.delegate && [self.delegate respondsToSelector:@selector(stopTimes)])
            {
                [self.delegate stopTimes];
            }
            
            BOOL isRight =  [self.rightDragView pointInsideImgView:[gesture locationInView:self.rightDragView]];
            BOOL isLeft  =  [self.leftDragView pointInsideImgView:[gesture locationInView:self.leftDragView]];
            _isDraggingRightOverlayView = NO;
            _isDraggingLeftOverlayView = NO;
            
            self.touchPointX = [gesture locationInView:self].x;
            if (isRight)
            {
                self.rightStartPoint = [gesture locationInView:self];
                _isDraggingRightOverlayView = YES;
                _isDraggingLeftOverlayView = NO;
            }
            else if (isLeft)
            {
                self.leftStartPoint = [gesture locationInView:self];
                _isDraggingRightOverlayView = NO;
                _isDraggingLeftOverlayView = YES;
            }
            
        } break;
        case UIGestureRecognizerStateChanged:
        {
            CGPoint point = [gesture locationInView:self];
            
            // Left
            if (_isDraggingLeftOverlayView)
            {
                CGFloat deltaX = point.x - self.leftStartPoint.x;
                CGPoint center = self.leftDragView.center;
                center.x += deltaX;
                CGFloat durationTime = (kScreenWidth-100)*2/10; // 最小范围2秒
                BOOL flag = (self.endPointX-point.x)>durationTime;
                
                if (center.x >= (50-kScreenWidth/2) && flag)
                {
                    self.leftDragView.center = center;
                    self.leftStartPoint = point;
                    self.startTime = (point.x+self.editScrollView.contentOffset.x)/self.IMG_Width;
                    self.topBorder.frame = CGRectMake(self.boderX+=deltaX/2, 0, self.boderWidth-=deltaX/2, 2);
                    self.bottomBorder.frame = CGRectMake(self.boderX+=deltaX/2, 50-2, self.boderWidth-=deltaX/2, 2);
                    self.startPointX = point.x;
                }
                CMTime startTime = CMTimeMakeWithSeconds((point.x+self.editScrollView.contentOffset.x)/self.IMG_Width, [self.delegate getCurrentTime]);
                
                // 只有视频播放的时候才能够快进和快退1秒以内
                if (self.delegate && [self.delegate respondsToSelector:@selector(seekTotime:withBefore:withAfter:)])
                {
                    [self.delegate seekTotime:startTime withBefore:kCMTimeZero withAfter:kCMTimeZero];
                }
            }
            else if (_isDraggingRightOverlayView)
            { // Right
                CGFloat deltaX = point.x - self.rightStartPoint.x;
                CGPoint center = self.rightDragView.center;
                center.x += deltaX;
                CGFloat durationTime = (kScreenWidth-100)*2/10; // 最小范围2秒
                BOOL flag = (point.x-self.startPointX)>durationTime;
                if (center.x <= (kScreenWidth-50+kScreenWidth/2) && flag)
                {
                    self.rightDragView.center = center;
                    self.rightStartPoint = point;
                    self.endTime = (point.x+self.editScrollView.contentOffset.x)/self.IMG_Width;
                    self.topBorder.frame = CGRectMake(self.boderX, 0, self.boderWidth+=deltaX/2, 2);
                    self.bottomBorder.frame = CGRectMake(self.boderX, 50-2, self.boderWidth+=deltaX/2, 2);
                    self.endPointX = point.x;
                }
                CMTime startTime = CMTimeMakeWithSeconds((point.x+self.editScrollView.contentOffset.x)/self.IMG_Width, [self.delegate getCurrentTime]);
                
                // 只有视频播放的时候才能够快进和快退1秒以内
                if (self.delegate && [self.delegate respondsToSelector:@selector(seekTotime:withBefore:withAfter:)])
                {
                    [self.delegate seekTotime:startTime withBefore:kCMTimeZero withAfter:kCMTimeZero];
                }
            }
            else
            { // 移动scrollView
                CGFloat deltaX = point.x - self.touchPointX;
                CGFloat newOffset = self.editScrollView.contentOffset.x-deltaX;
                CGPoint currentOffSet = CGPointMake(newOffset, 0);
                
                if (currentOffSet.x >= 0 && currentOffSet.x <= (self.editScrollView.contentSize.width-kScreenWidth))
                {
                    self.editScrollView.contentOffset = CGPointMake(newOffset, 0);
                    self.touchPointX = point.x;
                }
            }
        } break;
        case UIGestureRecognizerStateEnded:
        {
            if (self.delegate && [self.delegate respondsToSelector:@selector(startTimes)])
            {
                [self.delegate startTimes];
            }
        } break;
        default:
            break;
    }
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    if (self.delegate && [self.delegate respondsToSelector:@selector(stopTimes)])
    {
        [self.delegate stopTimes];
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if (self.delegate && [self.delegate respondsToSelector:@selector(startTimes)])
    {
        [self.delegate startTimes];
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [self letScrollViewScrollAndResetPlayerStartTime];
}




@end
